package org.jeecg.modules.wmhb.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.math.RandomUtils;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.constant.FillRuleConstant;
import org.jeecg.common.constant.UserConstant;
import org.jeecg.common.system.api.ISysBaseAPI;
import org.jeecg.common.system.vo.DictModel;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.FillRuleUtil;
import org.jeecg.modules.system.entity.SysUser;
import org.jeecg.modules.system.service.ISysDictService;
import org.jeecg.modules.wmhb.entity.*;
import org.jeecg.modules.wmhb.mapper.WmTaskBomMapper;
import org.jeecg.modules.wmhb.service.IWmTaskBomService;
import org.jeecg.modules.wmhb.vo.*;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.enmus.ExcelType;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @Description: 任务BOM
 * @Author: jeecg-boot
 * @Date:   2024-08-31
 * @Version: V1.0
 */
@Service
public class WmTaskBomServiceImpl extends ServiceImpl<WmTaskBomMapper, WmTaskBom> implements IWmTaskBomService {
    @Autowired
    private ISysDictService sysDictService;
    @Autowired
    ISysBaseAPI sysBaseApi;

    @Override
    public WmTaskBom importComponentBom(BOMNode bomNode, WmTask wmTaskRoot){
        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        WmTaskBom wmTaskBom = null;
        WmTaskBom wmTaskBomExist = getTaskBom(wmTaskRoot.getId(), bomNode.getCode());
        if(wmTaskBomExist == null) {
            wmTaskBom = new WmTaskBom();
            wmTaskBom.setWmTaskId(wmTaskRoot.getId());//设计起点任务ID
            wmTaskBom.setName(bomNode.getName());
            wmTaskBom.setCode(bomNode.getCode());
            wmTaskBom.setStatus(UserConstant.TASKBOM_PREPARE);
            wmTaskBom.setItemType(bomNode.getItemType());
            wmTaskBom.setNeedNum(bomNode.getQuantity());
            if(bomNode.getSingleWeight() > 0){
                wmTaskBom.setSingleWeight(bomNode.getSingleWeight());
                wmTaskBom.setTotalWeight(bomNode.getSingleWeight() * bomNode.getQuantity());
            }
            wmTaskBom.setUnitOfMeasure(bomNode.getUnitOfMeasure());
            wmTaskBom.setSpecification(bomNode.getSpecification());
            save(wmTaskBom);
        }
        else{
            wmTaskBom = wmTaskBomExist;
            wmTaskBom.setNeedNum(wmTaskBomExist.getNeedNum() + bomNode.getQuantity());
            if(bomNode.getSingleWeight() > 0){
                wmTaskBom.setTotalWeight(wmTaskBomExist.getTotalWeight() + bomNode.getSingleWeight() * bomNode.getQuantity());
            }
            updateById(wmTaskBom);
        }
        return wmTaskBom;
    };

    @Override
    public List<WmTaskBom> baoliaoListByWmTaskIds(List<String> idList){
        List<String> statusList = new ArrayList<>();
        statusList.add(UserConstant.TASKBOM_PREPARE);//初始状态 待报料
        statusList.add(UserConstant.TASKBOM_ORDERED);//已核减   已报料
        LambdaQueryWrapper<WmTaskBom> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(WmTaskBom::getWmTaskId, idList).in(WmTaskBom::getStatus, statusList);
        List<WmTaskBom> wmTaskBomList = list(queryWrapper);
        return wmTaskBomList;
    };

    @Override
    public List<WmTaskBom> noArriveListByWmTaskId(String wmTaskId){
        List<WmTaskBom> wmTaskBomList = new ArrayList<>();
        List<String> statusList = new ArrayList<>();
        statusList.add(UserConstant.TASKBOM_PREPARE);//初始状态 待报料
        statusList.add(UserConstant.TASKBOM_ORDERED);//已核减  已报料
        LambdaQueryWrapper<WmTaskBom> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(WmTaskBom::getWmTaskId, wmTaskId).notIn(WmTaskBom::getStatus, statusList);
        List<WmTaskBom> taskBomList = list(queryWrapper);
        for(WmTaskBom wmTaskBom: taskBomList){
            //物料未到齐
            if(wmTaskBom.getPurchaseNum() > wmTaskBom.getArriveNum()){
                wmTaskBomList.add(wmTaskBom);
            }
        }

        return wmTaskBomList;
    };

    @Override
    public List<WmTaskBom> listByWmTaskId(String wmTaskId){
        LambdaQueryWrapper<WmTaskBom> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(WmTaskBom::getWmTaskId, wmTaskId);
        List<WmTaskBom> wmTaskBomList = list(queryWrapper);
        return wmTaskBomList;
    };

    @Override
    public List<WmTaskBom> listByWmTaskIdAndVersion(String wmTaskId, String version){
        LambdaQueryWrapper<WmTaskBom> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(WmTaskBom::getWmTaskId, wmTaskId).eq(WmTaskBom::getCurrentVersion, version);
        List<WmTaskBom> wmTaskBomList = list(queryWrapper);
        return wmTaskBomList;
    };

    @Override
    public ModelAndView exportBomExcel(HttpServletRequest request, String taskbookType, List<WmTaskBom> wmTaskBomList){
        //1、获取分类数据
        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        List<String> itemTypeList = new ArrayList<>();
        Map<String, List<WmTaskBom>> mapDataList= new HashMap<>();
        for(WmTaskBom wmTaskBom: wmTaskBomList){
            if(!StringUtils.isEmpty(user.getWorkNo()) && !StringUtils.isEmpty(wmTaskBom.getProcessNo())) {
                wmTaskBom.setSeriesNo(user.getWorkNo() + "." + wmTaskBom.getProcessNo());
            }
            else if(StringUtils.isEmpty(user.getWorkNo()) && !StringUtils.isEmpty(wmTaskBom.getProcessNo())) {
                String code = "CK." + user.getUsername().toUpperCase() + "." + wmTaskBom.getProcessNo();
                wmTaskBom.setSeriesNo(code);
            }
            else{
                SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
                int random = RandomUtils.nextInt(9000) + 1000; //0到n-1之间的随机数 n=9000
                String code = "CK." + format.format(new Date()) + random;
                wmTaskBom.setSeriesNo(code);
            }

            List<WmTaskBom> wmTaskBomListOfSheet = null;
            if(!itemTypeList.contains(wmTaskBom.getItemType())){
                itemTypeList.add(wmTaskBom.getItemType());
                wmTaskBomListOfSheet = new ArrayList<>();
            }
            else{
                wmTaskBomListOfSheet = mapDataList.get(wmTaskBom.getItemType());
            }
            wmTaskBomListOfSheet.add(wmTaskBom);
            mapDataList.put(wmTaskBom.getItemType(), wmTaskBomListOfSheet);

            //更新报料序号，报料时才更新序号
            updateById(wmTaskBom);
        }

        // 2、遍历数据，添加多个 sheet 的数据及其对应的实体类
        List<Map<String, Object>> dataList = new ArrayList<>();
        for (String key : mapDataList.keySet()) {
            String ItemText = sysDictService.queryDictTextByKey(UserConstant.ITEM_TYPE, key);
            ItemText = !StringUtils.isEmpty(ItemText) ? ItemText : key;
            Map<String, Object> map = new HashMap<>();
            map.put(NormalExcelConstants.PARAMS, new ExportParams(null, ItemText, ExcelType.XSSF));

            if(taskbookType.equals(UserConstant.TASKBOOK_TYPE_PRODUCE)) {
                //机械报料
                map.put(NormalExcelConstants.CLASS, WmApplyBomVo.class);
                List<WmApplyBomVo> sheetList = new ArrayList<WmApplyBomVo>();
                List<WmTaskBom> cateTaskBomList = mapDataList.get(key);
                for(WmTaskBom wmTaskBom: cateTaskBomList){
                    WmTaskbook wmTaskbook = baseMapper.selectTaskbookByTaskId(wmTaskBom.getWmTaskId());
                    WmTask wmTask = baseMapper.selectTaskByTaskId(wmTaskBom.getWmTaskId());
                    //机械生产任务书
                    WmApplyBomVo wmApplyBom = new WmApplyBomVo();
                    if (!StringUtils.isEmpty(wmTask.getDesignUserId())) {
                        SysUser designUser = baseMapper.selectUserById(wmTask.getDesignUserId());
                        wmApplyBom.setTechnology(designUser.getRealname());
                    }
                    if (!StringUtils.isEmpty(wmTask.getProcessUserId())) {
                        SysUser processUser = baseMapper.selectUserById(wmTask.getProcessUserId());
                        wmApplyBom.setProcess(processUser.getRealname());
                    }
                    wmApplyBom.setName(wmTaskBom.getName());
                    wmApplyBom.setCode(wmTaskBom.getCode());
                    wmApplyBom.setNeedNum(wmTaskBom.getNeedNum());
                    wmApplyBom.setUnitOfMeasure(wmTaskBom.getUnitOfMeasure());
                    wmApplyBom.setSpecification(wmTaskBom.getSpecification());
                    wmApplyBom.setSeriesNo(wmTaskBom.getSeriesNo());
                    wmApplyBom.setGotowhere(wmTaskBom.getGotowhere());
                    wmApplyBom.setMaterial(wmTaskBom.getMaterial());
                    wmApplyBom.setSize(wmTaskBom.getSize());
                    wmApplyBom.setCaiLiao(wmTaskBom.getCaiLiao());
                    wmApplyBom.setGbNumber(wmTaskBom.getGbNumber());
                    wmApplyBom.setMingCheng(wmTaskBom.getMingCheng());
                    wmApplyBom.setOtherRequire(wmTaskBom.getOtherRequire());
                    wmApplyBom.setParam(wmTaskBom.getRemark());
                    wmApplyBom.setTaskNo(wmTaskbook.getCode());
                    wmApplyBom.setSeriesNoAuto(wmTaskBom.getSeriesNo());
                    sheetList.add(wmApplyBom);
                }
                map.put(NormalExcelConstants.DATA_LIST, sheetList);
            }
            else{
                //电仪报料
                map.put(NormalExcelConstants.CLASS, WmApplyBomDyVo.class);
                List<WmApplyBomDyVo> sheetList = new ArrayList<WmApplyBomDyVo>();
                List<WmTaskBom> cateTaskBomList = mapDataList.get(key);
                Integer sn = 0;
                for(WmTaskBom wmTaskBom: cateTaskBomList){
                    sn++;
                    WmTaskbook wmTaskbook = baseMapper.selectTaskbookByTaskId(wmTaskBom.getWmTaskId());
                    WmContract wmContract = baseMapper.selectContractByContractId(wmTaskbook.getWmContractId());
                    //机械生产任务书
                    WmApplyBomDyVo wmApplyBomDy = new WmApplyBomDyVo();
                    wmApplyBomDy.setSn(sn.toString());
                    wmApplyBomDy.setSeriesNoAuto(wmTaskBom.getSeriesNo());
                    wmApplyBomDy.setName(wmTaskBom.getName());
                    wmApplyBomDy.setCode(wmTaskBom.getCode());
                    wmApplyBomDy.setNeedNum(wmTaskBom.getNeedNum());
                    wmApplyBomDy.setUnitOfMeasure(wmTaskBom.getUnitOfMeasure());
                    wmApplyBomDy.setSpecification(wmTaskBom.getSpecification());
                    String importUnit = sysDictService.queryDictTextByKey(UserConstant.UNIT_OF_MESSURE, wmTaskBom.getUnitOfMeasure());
                    wmApplyBomDy.setImportUnit(importUnit);
                    wmApplyBomDy.setTaskNo(wmTaskbook.getCode());
                    wmApplyBomDy.setGotowhere(wmTaskBom.getGotowhere());
                    wmApplyBomDy.setContractNo(wmContract.getCode());
                    sheetList.add(wmApplyBomDy);
                }
                map.put(NormalExcelConstants.DATA_LIST, sheetList);
            }

            dataList.add(map);
        }

        SimpleDateFormat format = new SimpleDateFormat("MMddHHmm");
        String fileName = "BOM_".concat(format.format(new Date()));
        ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
        mv.addObject(NormalExcelConstants.FILE_NAME, fileName);
        mv.addObject(NormalExcelConstants.MAP_LIST, dataList);
        return mv;
    };

    private ModelAndView exportBomExcelSingle(HttpServletRequest request, List<WmTaskBom> list){
        ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
        List<WmApplyBomVo> wmOrderBomVoList = new ArrayList<WmApplyBomVo> ();
        for(int j=0; j<10; j++){
            WmApplyBomVo wmOrderBom = new WmApplyBomVo();
            wmOrderBom.setName("张三"+j);
            wmOrderBom.setNeedNum(18D+j);
            wmOrderBom.setUnitOfMeasure("GE");
            wmOrderBomVoList.add(wmOrderBom);
        }

        SimpleDateFormat format = new SimpleDateFormat("MMddHHmm");
        String fileName = "BOM_".concat(format.format(new Date()));
        //导出文件名称//此处设置的filename无效 ,前端会重更新设置一下
        mv.addObject(NormalExcelConstants.FILE_NAME, fileName);
        //注解对象Class
        mv.addObject(NormalExcelConstants.CLASS, WmApplyBomVo.class);
        //自定义导出字段
        //mv.addObject(NormalExcelConstants.EXPORT_FIELDS,"name,keyWord,punchTime");
        //自定义表格参数
        mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("报料单", "报料单", ExcelType.XSSF));
        //导出数据列表
        mv.addObject(NormalExcelConstants.DATA_LIST, wmOrderBomVoList);
        return mv;
    };

    @Override
    public void updatePurchaseNum(WmApplyBomVo wmApplyBomVo){
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String orderTime = format.format(new Date());
        LambdaUpdateWrapper<WmTaskBom> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.set(WmTaskBom::getPurchaseNum, wmApplyBomVo.getPurchaseNum())
                .set(WmTaskBom::getOrderTime, orderTime) //报料时间
                .set(WmTaskBom::getStatus, UserConstant.TASKBOM_ORDERED)
                .eq(WmTaskBom::getSeriesNo, wmApplyBomVo.getSeriesNo());
        update(null, updateWrapper);
    };

    @Override
    public void updateOrderDetail(WmOrderBomVo wmOrderBomVo){
        String newStatus = "";
        String seriesNo = "";
        if(!StringUtils.isEmpty(wmOrderBomVo.getOrderDate())) {
            newStatus = UserConstant.TASKBOM_PURCHASED;
        }
        if(!StringUtils.isEmpty(wmOrderBomVo.getArriveDate())) {
            newStatus = UserConstant.TASKBOM_ARRIVED;
        }

        if(!StringUtils.isEmpty(wmOrderBomVo.getSeriesNo())) {
            //生产车间序号
            seriesNo = wmOrderBomVo.getSeriesNo();
        }
        else if(!StringUtils.isEmpty(wmOrderBomVo.getSeriesNo2())) {
            //自控电气序号
            seriesNo = wmOrderBomVo.getSeriesNo2();
        }

        if(!StringUtils.isEmpty(newStatus) && !StringUtils.isEmpty(seriesNo)){
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
            LambdaUpdateWrapper<WmTaskBom> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.set(WmTaskBom::getArriveNum, wmOrderBomVo.getQuantity())
                    .set(WmTaskBom::getStatus, newStatus)
                    .eq(WmTaskBom::getSeriesNo, seriesNo);

            //如果有到货日期
            if(!StringUtils.isEmpty(wmOrderBomVo.getArriveDate())){
                try {
                    Date arriveTime = format.parse(wmOrderBomVo.getArriveDate());
                    updateWrapper.set(WmTaskBom::getArriveTime, arriveTime); //物料到货日期
                }
                catch (ParseException e) {}
            }
            //如果有采购日期
            if(!StringUtils.isEmpty(wmOrderBomVo.getOrderDate())){
                try {
                    Date purchaseTime = format.parse(wmOrderBomVo.getOrderDate());
                    updateWrapper.set(WmTaskBom::getPurchaseTime, purchaseTime);  //采购订货日期
                }
                catch (ParseException e) {}
            }
            update(null, updateWrapper);
        }
    };

    @Override
    public List<WmTaskBom> listGroupByWmTaskIds(List<String> idList){
        List<WmTaskBom> wmTaskBomList = baseMapper.listGroupByWmTaskIds(idList);
        return wmTaskBomList;
    };

    @Override
    public List<WmTaskBom> listByWmTaskIds(List<String> idList){
        LambdaQueryWrapper<WmTaskBom> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(WmTaskBom::getWmTaskId, idList);
        List<WmTaskBom> wmTaskBomList = list(queryWrapper);
        return wmTaskBomList;
    };

    @Override
    public void consumeBom(String wmTaskId){
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String consumeTime = format.format(new Date());
        LambdaUpdateWrapper<WmTaskBom> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.set(WmTaskBom::getConsumeTime, consumeTime)
                .set(WmTaskBom::getStatus, UserConstant.TASKBOM_USED)
                .eq(WmTaskBom::getWmTaskId, wmTaskId)
                .gt(WmTaskBom::getPurchaseNum, 0)
                .gt(WmTaskBom::getArriveNum, 0)
                .isNotNull(WmTaskBom::getArriveTime);
        update(null, updateWrapper);
    };

    @Override
    public String selectWmTaskIdBySeriesNo(String seriesNo){
        LambdaQueryWrapper<WmTaskBom> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(WmTaskBom::getSeriesNo, seriesNo).orderByDesc(WmTaskBom::getCreateTime).last("LIMIT 1");
        WmTaskBom wmTaskBom = getOne(queryWrapper);
        return wmTaskBom != null ? wmTaskBom.getWmTaskId() : null;
    };

    @Override
    public List<WmTaskBom> orderBomList(){
        List<String> statusList = new ArrayList<>();
        statusList.add(UserConstant.TASKBOM_PURCHASED);    //已采购
        statusList.add(UserConstant.TASKBOM_ORDERED);      //已核减

        LambdaQueryWrapper<WmTaskBom> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(WmTaskBom::getStatus, statusList);
        List<WmTaskBom> wmTaskBomList = list(queryWrapper);
        return wmTaskBomList;
    };

    private WmTaskBom getTaskBom(String wmTaskId, String code){
        LambdaQueryWrapper<WmTaskBom> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(WmTaskBom::getWmTaskId, wmTaskId).eq(WmTaskBom::getCode, code).last("LIMIT 1");
        WmTaskBom wmTaskBom = getOne(queryWrapper);
        return wmTaskBom;
    };

    @Override
    public void updateTaskbom(WmTask wmTaskRoot, WmTask wmTaskParent, WmTask wmTaskNew, WmTask wmTaskOriginal){
        WmTaskBom wmTaskBom = null;
        //根据根任务ID和编码查询当前编辑的任务是否存在任务BOM
        WmTaskBom wmTaskBomExist = getTaskBom(wmTaskRoot.getId(), wmTaskNew.getCode());
        //有原始任务（编辑任务）
        if(wmTaskOriginal != null){
            if(!StringUtils.isEmpty(wmTaskNew.getItemOrProduct())) {
                //编辑前后产品类型不一致
                if (!wmTaskOriginal.getItemOrProduct().equals(wmTaskNew.getItemOrProduct())) {
                    //将产品变成物料
                    if (wmTaskNew.getItemOrProduct().equals(UserConstant.PRODUCT_ITEM)) {
                        //是否存在任务物料
                        if (wmTaskBomExist == null) {
                            //不存在则新增
                            saveTaskBom(wmTaskRoot, wmTaskParent, wmTaskNew);
                        } else {
                            //存在则编辑（在现有任务BOM上增加数量）
                            wmTaskBom = wmTaskBomExist;
                            Double newNeedNum = wmTaskBomExist.getNeedNum() + wmTaskNew.getQuantity() * wmTaskParent.getQuantity();
                            wmTaskBom.setNeedNum(newNeedNum);
                            updateById(wmTaskBom);
                        }
                    }
                    //将物料变成产品
                    else {
                        if (wmTaskBomExist != null) {
                            wmTaskBom = wmTaskBomExist;
                            //在现有任务BOM上减少数量
                            Double newNeedNum = wmTaskBomExist.getNeedNum() - wmTaskNew.getQuantity() * wmTaskParent.getQuantity();
                            if (newNeedNum > 0) {
                                wmTaskBom.setNeedNum(newNeedNum);
                                updateById(wmTaskBom);
                            } else {
                                removeById(wmTaskBom.getId());
                            }
                        } else {
                            //没有的话就不减了（异常数据）
                        }
                    }
                } else {
                    //产品类型一致
                    if (!wmTaskNew.getQuantity().equals(wmTaskOriginal.getQuantity())) {
                        //数量不一致
                        if (wmTaskNew.getItemOrProduct().equals(UserConstant.PRODUCT_ITEM)) {
                            //都是物料
                            if (wmTaskBomExist == null) {
                                //不存在则新增
                                saveTaskBom(wmTaskRoot, wmTaskParent, wmTaskNew);
                            } else {
                                //存在则更新数量,减少原有数量，增加新增数量
                                wmTaskBom = wmTaskBomExist;
                                Double newNeedNum = wmTaskBomExist.getNeedNum() - wmTaskOriginal.getQuantity() * wmTaskParent.getQuantity() + wmTaskNew.getQuantity() * wmTaskParent.getQuantity();
                                wmTaskBom.setNeedNum(newNeedNum);
                                updateById(wmTaskBom);
                            }
                        } else {
                            //都是产品do nothing
                        }
                    } else {
                        //数量一致do nothing
                    }
                }
            }
        }
        //没有原始任务（新增任务）
        else{
            //新增物料类型
            if (wmTaskNew.getItemOrProduct().equals(UserConstant.PRODUCT_ITEM)) {
                //是否存在任务物料
                if (wmTaskBomExist == null) {
                    //不存在则新增
                    saveTaskBom(wmTaskRoot, wmTaskParent, wmTaskNew);
                }
                else{
                    //存在则编辑（在现有任务BOM上增加数量）
                    wmTaskBom = wmTaskBomExist;
                    Double newNeedNum = wmTaskBomExist.getNeedNum() + wmTaskNew.getQuantity() * wmTaskParent.getQuantity();
                    wmTaskBom.setNeedNum(newNeedNum);
                    updateById(wmTaskBom);
                }
            }
            //新增产品类型
            else{
                //do nothing
            }
        }
    };

    //新增任务物料
    private void saveTaskBom(WmTask wmTaskRoot, WmTask wmTaskParent, WmTask wmTaskNew){
        //不存在则新增
        WmTaskBom wmTaskBom = new WmTaskBom();
        String code = (String) FillRuleUtil.executeRule(FillRuleConstant.BOM_ORDER, null);
        wmTaskBom.setWmTaskId(wmTaskRoot.getId());//设计起点任务ID
        wmTaskBom.setName(wmTaskNew.getName());
        wmTaskBom.setCode(wmTaskNew.getCode());
        wmTaskBom.setStatus(UserConstant.TASKBOM_PREPARE);
        //wmTaskBom.setSeriesNo(code);
        wmTaskBom.setItemType(wmTaskNew.getItemType());
        wmTaskBom.setNeedNum(wmTaskNew.getQuantity() * wmTaskParent.getQuantity());
        wmTaskBom.setUnitOfMeasure(wmTaskNew.getUnitOfMeasure());
        wmTaskBom.setSpecification(wmTaskNew.getSpecification());
        save(wmTaskBom);
    };

    @Override
    public List<WmTaskBom> importMaterialBom(List<WmMaterialVo> wmMaterialVoList, WmTask wmTaskRoot){
        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        List<WmTaskBom> wmTaskBomList = new ArrayList<>();
        for(WmMaterialVo wmMaterialVo: wmMaterialVoList) {
            //只有序号一列，金蝶名称金蝶编码名称三列都为空的忽略
            if(!StringUtils.isEmpty(wmMaterialVo.getSort()) && StringUtils.isEmpty(wmMaterialVo.getName()) && StringUtils.isEmpty(wmMaterialVo.getCode()) && StringUtils.isEmpty(wmMaterialVo.getMingCheng())){
                continue;
            }

            WmTaskBom wmTaskBom = new WmTaskBom();
            wmTaskBom.setWmTaskId(wmTaskRoot.getId());//设计起点任务ID
            if(!StringUtils.isEmpty(wmMaterialVo.getName())) {
                wmTaskBom.setName(wmMaterialVo.getName());
            }
            else{
                wmTaskBom.setName(wmMaterialVo.getMingCheng());
            }
            wmTaskBom.setCode(wmMaterialVo.getCode());
            wmTaskBom.setStatus(UserConstant.TASKBOM_PREPARE);
            wmTaskBom.setItemType(UserConstant.ITEM_TYPE_MATERIAL);
            wmTaskBom.setNeedNum(wmMaterialVo.getTotalWeight());
            if (wmMaterialVo.getTotalWeight() > 0) {
                wmTaskBom.setTotalWeight(wmMaterialVo.getTotalWeight());
            }
            wmTaskBom.setUnitOfMeasure(wmMaterialVo.getUnitOfMeasure());
            wmTaskBom.setSpecification(wmMaterialVo.getSpecification());
            wmTaskBom.setMaterial(wmMaterialVo.getMaterial());
            wmTaskBom.setProcessNo(wmMaterialVo.getProcessNo());
            wmTaskBom.setGotowhere(wmMaterialVo.getGotowhere());
            wmTaskBom.setSize(wmMaterialVo.getSize());
            wmTaskBom.setCaiLiao(wmMaterialVo.getCaiLiao());
            wmTaskBom.setGuiGe(wmMaterialVo.getGuiGe());
            wmTaskBom.setMingCheng(wmMaterialVo.getMingCheng());
            wmTaskBom.setRemark(wmMaterialVo.getRemark());
            wmTaskBom.setCurrentVersion(wmTaskRoot.getCurrentVersion());
            save(wmTaskBom);
            wmTaskBomList.add(wmTaskBom);
        }

        //新增20条备用的材料
        for(int i=0; i<20; i++){
            WmTaskBom wmTaskBom = new WmTaskBom();
            wmTaskBom.setName("备用" + (i + 1));
            wmTaskBom.setWmTaskId(wmTaskRoot.getId());//设计起点任务ID
            wmTaskBom.setStatus(UserConstant.TASKBOM_PREPARE);
            wmTaskBom.setItemType(UserConstant.ITEM_TYPE_MATERIAL);
            wmTaskBom.setCurrentVersion(wmTaskRoot.getCurrentVersion());
            //save(wmTaskBom);
            //wmTaskBomList.add(wmTaskBom);
        }

        return wmTaskBomList;
    };

    @Override
    public List<WmTaskBom> importBuyBom(List<WmBuyVo> wmBuyVoList, WmTask wmTaskRoot){
        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        List<WmTaskBom> wmTaskBomList = new ArrayList<>();
        for(WmBuyVo wmBuyVo: wmBuyVoList) {
            //只有序号一列的忽略
            if(!StringUtils.isEmpty(wmBuyVo.getSort()) && StringUtils.isEmpty(wmBuyVo.getName()) && StringUtils.isEmpty(wmBuyVo.getCode()) && StringUtils.isEmpty(wmBuyVo.getMingCheng())){
                continue;
            }

            WmTaskBom wmTaskBom = new WmTaskBom();
            wmTaskBom.setWmTaskId(wmTaskRoot.getId());//设计起点任务ID
            if(!StringUtils.isEmpty(wmBuyVo.getName())) {
                wmTaskBom.setName(wmBuyVo.getName());
            }
            else{
                wmTaskBom.setName(wmBuyVo.getMingCheng());
            }
            wmTaskBom.setCode(wmBuyVo.getCode());
            wmTaskBom.setStatus(UserConstant.TASKBOM_PREPARE);
            wmTaskBom.setItemType(UserConstant.ITEM_TYPE_BUY);
            wmTaskBom.setNeedNum(wmBuyVo.getQuantity());
            wmTaskBom.setUnitOfMeasure(wmBuyVo.getUnitOfMeasure());
            wmTaskBom.setSpecification(wmBuyVo.getSpecification());
            wmTaskBom.setMaterial(wmBuyVo.getMaterial());
            wmTaskBom.setProcessNo(wmBuyVo.getProcessNo());
            wmTaskBom.setGotowhere(wmBuyVo.getGotowhere());
            wmTaskBom.setSize(wmBuyVo.getSize());
            wmTaskBom.setMingCheng(wmBuyVo.getMingCheng());
            wmTaskBom.setOtherRequire(wmBuyVo.getOtherRequire());
            wmTaskBom.setGbNumber(wmBuyVo.getGbNumber());
            wmTaskBom.setCaiLiao(wmBuyVo.getCaiLiao());
            wmTaskBom.setCurrentVersion(wmTaskRoot.getCurrentVersion());
            save(wmTaskBom);
            wmTaskBomList.add(wmTaskBom);
        }

        return wmTaskBomList;
    };

    @Override
    public WmTaskBom queryBySeriesNo(String seriesNo){
        LambdaQueryWrapper<WmTaskBom> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(WmTaskBom::getSeriesNo, seriesNo).orderByDesc(WmTaskBom::getCreateTime).last("LIMIT 1");
        WmTaskBom wmTaskBom = getOne(queryWrapper);
        return wmTaskBom;
    };

    @Override
    public List<WmTaskBom> queryByTaskAndVersion(WmTask wmTask, String itemType){
        LambdaQueryWrapper<WmTaskBom> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(WmTaskBom::getWmTaskId, wmTask.getId()).isNotNull(WmTaskBom::getCode).eq(WmTaskBom::getItemType, itemType);
        if(wmTask.getCurrentVersion() == null){
            queryWrapper.isNull(WmTaskBom::getCurrentVersion);
        }
        else{
            queryWrapper.eq(WmTaskBom::getCurrentVersion, wmTask.getCurrentVersion());
        }
        List<WmTaskBom> wmTaskBomList = list(queryWrapper);
        return wmTaskBomList;
    };
}

